package com.canbot.u05.utils;

import android.os.Environment;
import android.support.annotation.NonNull;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
        /** * @param saveDir * @return * @throws IOException * 判断下载目录是否存在 */
        public static  String isExistDir(String saveDir) throws IOException { // 下载位置
                File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
                if (!downloadFile.mkdirs()) {
                        downloadFile.createNewFile();
                }
                String savePath = downloadFile.getAbsolutePath();
                return savePath;
        }

        /** * @param url * @return * 从下载连接中解析出文件名 */ @NonNull
        public static String getNameFromUrl(String url) {
                return url.substring(url.lastIndexOf("/") + 1);
        }

        /**
         * 删除文件
         *
         * @param cmd
         * @return
         */
        public static boolean execCmd(String cmd) {
                boolean result = false;
                Process process = null;
                OutputStream out = null;
                DataOutputStream dataOutputStream = null;
                try {
                        process = Runtime.getRuntime().exec("su");
                        out = process.getOutputStream();
                        dataOutputStream = new DataOutputStream(out);

                        dataOutputStream.writeBytes(cmd + "\n");
                        // 提交命令
                        dataOutputStream.flush();
                        dataOutputStream.writeBytes("exit\n");
                        dataOutputStream.flush();
                        byte b[] = new byte[512];
                        int r = 0;
                        StringBuffer sbf = new StringBuffer();
                        while ((r = process.getErrorStream().read(b, 0, 512)) > -1) {
                                sbf.append(new String(b, 0, r));
                                System.out.println(new String(b, 0, r));
                        }
                        String sbftostring = sbf.toString().trim();
                        if (sbftostring != null && sbftostring.contains("Failure")) {
                                result = false;
                        } else {
                                result = true;
                        }

                        dataOutputStream.close();
                        out.close();
                } catch (Exception e) {
                        e.printStackTrace();
                        result = false;
                }
                return result;
        }
        public static boolean fileIsExists(String path) {
                try {
                        File file = new File(path);
                        if (file.exists() && file.isFile()) {
                                return true;
                        }
                }
                catch (Exception e) {
                        return false;
                }
                return false;
        }

        public static int getFilesLength(String dir, final String filter) {
                int n = 0;
                File file = new File(dir);
                if (file != null && file.isDirectory()) {
                        File[] files = file.listFiles(new FilenameFilter() {

                                @Override
                                public boolean accept(File dir, String name) {
                                        // TODO Auto-generated method stub
                                        if (name.endsWith(filter)) {
                                                return true;
                                        }
                                        return false;
                                }
                        });

                        if (files != null) {
                                n = files.length;
                        }

                }
                return n;
        }

        /**
         * 创建文件夹
         *
         * @param dirPath
         */
        public static void createDir(String dirPath) {
                File fileDir = new File(dirPath);
                if (!fileDir.exists()) { // 若不存在
                        fileDir.mkdirs();
                }
        }

        /**
         * 删除文件
         *
         * @param dirPath
         */
        public static void deleteFile(String dirPath) {
                File fileDir = new File(dirPath);
                if (fileDir.exists()) { // 若存在
                        fileDir.delete();
                }
        }

        /**
         * 重命名文件夹
         *
         * @param dirPath
         * @param newName
         */
        public static void reNameDir(String dirPath, String oldName,
                                     String newName) {
                File fileDir = new File(dirPath + oldName);
                if (!fileDir.exists()) {
                        return;
                }
                fileDir.renameTo(new File(dirPath + newName));

        }

        /**
         * 复制文件
         *
         * @param dirPath
         */
        public static boolean copyFile(String resourcePath, String targetPath) {
                try {
                        int byteread = 0;
                        File oldfile = new File(resourcePath);
                        File targetfile = new File(targetPath);
                        if (targetfile.exists()) {
                                targetfile.delete();
                        }
                        if (oldfile.exists()) { // 文件存在时
                                InputStream inStream = new FileInputStream(resourcePath); // 读入原文件
                                @SuppressWarnings("resource")
                                FileOutputStream fs = new FileOutputStream(targetPath);
                                byte[] buffer = new byte[1444];
                                while ((byteread = inStream.read(buffer)) != -1) {
                                        fs.write(buffer, 0, byteread);
                                }
                                inStream.close();
                                return true;
                        }
                }
                catch (Exception e) {
                        System.out.println("复制单个文件操作出错");
                        e.printStackTrace();

                }
                return false;
        }

        /**
         * 遍历指定路径下所有文件名
         *
         * @param filePath
         * @return
         */
        public static List<String> seekFiles(String filePath) {
                File file = new File(filePath);
                if (file.exists()) {
                        List<String> fileName = new ArrayList<String>();
                        File[] files = file.listFiles();
                        for (File file2 : files) {
                                if (file2.isDirectory()) {
                                        fileName.add(file2.getName());
                                }
                        }
                        return fileName;
                }
                return null;
        }

        /**
         * 递归删除目录下的所有文件及子目录下所有文件
         *
         * @param dir 将要删除的文件目录
         * @return boolean Returns "true" if all deletions were successful.
         * If a deletion fails, the method stops attempting to
         * delete and returns "false".
         */
        public static boolean deleteDir(File dir) {
                if (dir.isDirectory()) {
                        String[] children = dir.list();
                        //递归删除目录中的子目录下
                        for (int i = 0; i < children.length; i++) {
                                boolean success = deleteDir(new File(dir, children[i]));
                                if (!success) {
                                        return false;
                                }
                        }
                }
                // 目录此时为空，可以删除
                return dir.delete();
        }
}
